package com.huike;

import io.jsonwebtoken.*;

import java.util.Date;

public class JWTDemo {
    //设置签名
    static String signature = "itheima";

    public static void main(String[] args) {
        /**
         * 加密
         */
        //1.构建jwt
        JwtBuilder builder = Jwts.builder();
        //2.设置Header
        String token = builder.setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256") //加密算法
                //3.封装PayLoad里的信息
                .claim("username", "zhangsan")
                .claim("name", "张三")
                .claim("age", 23)
                .claim("sex", "男")
                //3.设置PayLoad超时时间
                .setExpiration(new Date(System.currentTimeMillis() + (long) (1000 * 60 * 60)))
                .setId("121212121")
                //4.设置加密signatrue;
                .signWith(SignatureAlgorithm.HS256, signature)
                .compact();
        System.out.println(token);

        /**
         * 解密
         */
        JwtParser parser = Jwts.parser();
        Jws<Claims> claimsJws = parser.setSigningKey(signature).parseClaimsJws(token);
        Claims body = claimsJws.getBody();
        //1.获取PayLoad
        System.out.println(body.get("username"));
        System.out.println(body.get("name"));
        System.out.println(body.get("age"));
        System.out.println(body.get("sex"));
        System.out.println(body.getId());
        System.out.println(body.getExpiration());
        System.out.println(body.getSubject());
        //2.获取Header
        System.out.println(claimsJws.getHeader());
        //3.获取signatrue
        System.out.println(claimsJws.getSignature());
    }


}
